package com.towing.server;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.towing.client.DBConnection;
import com.towing.client.UserBean;



public class MyDBConnection extends RemoteServiceServlet implements DBConnection {



	private static final long serialVersionUID = 1L;

	public MyDBConnection() {
		try{
			Class.forName("com.mysql.jdbc.Driver");

		} catch (Exception e){
			System.out.println("JDBC-ODBC driver failed to load.");
			return;
		}
	}

	private UserBean createBean(ResultSet rs) throws SQLException {

		UserBean user = new UserBean();

		user.setEmail(rs.getString("Email"));
		user.setFirstName(rs.getString("FirstName"));
		user.setLastName(rs.getString("LastName"));
		user.setLastName(rs.getString("UserName"));
		user.setPassword(rs.getString("Password"));
		user.setType(rs.getInt("Type"));

		return user;
	}

	@Override
	public UserBean validateLogin(String uname, String pword) {
		Connection con = null;
		try {
			System.out.println(uname+" == "+pword);
			con = DriverManager.getConnection("jdbc:mysql://sql09.freemysql.net","hari666","q3procn");
			PreparedStatement stmt = con.prepareStatement("select * from user where UserName = ? and Password = ? ");
			stmt.setString(1, uname);
			stmt.setString(2, pword);
			ResultSet rs = stmt.executeQuery();
			if (rs.next()) {
				UserBean user = createBean(rs);
				HttpServletRequest request = this.getThreadLocalRequest();
				HttpSession session = request.getSession();
				session.setAttribute("user" , user);
				return user;
			}
		} catch (SQLException e) {
			
		} finally {
			if (con != null) {
				try {
					con.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}
		return null;
	}

}
